/*
 *    Copyright 2022 The DSMS Authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.dsms.modules.util;

import com.ceph.rados.Rados;
import com.ceph.rados.exceptions.RadosException;
import com.dsms.common.constant.RadosConfigConst;
import com.dsms.common.constant.SystemConst;
import com.dsms.common.util.ObjectUtil;
import com.dsms.dfsbroker.cluster.model.Cluster;
import com.dsms.dfsbroker.cluster.service.IClusterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.EnumSet;

@Slf4j
public enum RadosSingleton {
    INSTANCE;

    @Autowired
    IClusterService clusterService;
    private Rados rados;

    private RadosSingleton() {
    }

    public Rados getRados() {
        //rados.shutdown() makes rados' pointer null,not rados null,so check rados property for null here
        if (ObjectUtil.checkObjFieldContainNull(rados)) {
            rados = new Rados(SystemConst.DSMS_STORAGE_USER);
            Cluster currentBindCluster = clusterService.getCurrentBindCluster();
            try {
                rados.confSet(RadosConfigConst.MON_HOST, currentBindCluster.getClusterAddress());
                rados.confSet(RadosConfigConst.ADMIN_KEY, currentBindCluster.getAdminKey());
                rados.connect();
            } catch (RadosException e) {
                log.error("connect rados error:{}", e.getMessage(), e);
                throw new RuntimeException(e);
            }
        }
        return rados;
    }

    public void shutdownRados() {
        if (rados != null) {
            rados.shutDown();
        }
    }

    private void setClusterService(IClusterService clusterService) {
        this.clusterService = clusterService;
    }

    @Component
    public static class SetClusterService {
        @Autowired
        IClusterService clusterService;

        @PostConstruct
        public void postConstruct() {
            for (RadosSingleton radosSingleton : EnumSet.allOf(RadosSingleton.class)) {
                radosSingleton.setClusterService(clusterService);
            }
        }
    }
}
